package router

import (
	"GOPAAS/api/v1"
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/controllers"
	"GOPAAS/internal/app/middleware"
	"GOPAAS/internal/utils"
	"github.com/gin-contrib/multitemplate"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func NewRouter() *gin.Engine {
	router := gin.Default()

	store := cookie.NewStore([]byte(config.Conf.SessionKey))
	// 设置session中间件，参数mysession，指的是session的名字，也是cookie的名字
	// store是前面创建的存储引擎，我们可以替换成其他存储引擎
	router.Use(sessions.Sessions(config.Conf.SessionKey, store))
	router.HTMLRender = createMyRender(multitemplate.New())
	router.NoRoute(func(c *gin.Context) {
		//c.HTML(http.StatusOK, "404", gin.H{})
	})
	// 简单的路由组: v1
	api := router.Group("/api", middleware.Api())
	{
		av1 := api.Group("/v1")
		{
			//登录
			av1.POST("/login", v1.PostLogin)
			av1.POST("/signup", v1.PostSignup)
			//获取国家
			av1.GET("/country", v1.GetCountry)
			//获取省
			av1.GET("/state/:country_id", v1.GetSate)
			//获取市
			av1.GET("/city/:state_id", v1.GetCity)
			av1.GET("/area/:city_id", v1.GetArea)
			av1.Use(middleware.CheckApiLogin())
			//退出
			av1.POST("/sign-out", func(c *gin.Context) {
				session := sessions.Default(c)
				session.Clear()
				err := session.Save()
				if err != nil {
					utils.Error(c, 1, "退出失败", nil)
					return
				}
				utils.Success(c, "退出成功", nil)
			})
		}
	}

	web := router.Group("/web", middleware.Web())
	{
		web.GET("/login", controllers.Login)
		web.GET("/mqtt", controllers.Mqtt)
		web.GET("/image/:size", controllers.Image)
		webUser := web.Group("/user", middleware.CheckWebLogin())
		{
			webUser.GET("/index", controllers.Index)
			webUser.GET("/list", controllers.UserList)
			webUser.GET("/edit/:user_id", controllers.UserEdit)
		}
	}
	router.Static("/assets", "./web/static")

	return router
}
